from app.celery import celery
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from fake_useragent import UserAgent
from app.models.user import User
import time
import random

@celery.task
def run(word):
    Task().baidu()
    return '{} ok'.format(word)


class Task(object):
    def __init__(self):
        ua = UserAgent()
        options = webdriver.ChromeOptions()
        options.add_argument("user-agent={}".format(ua.random))
        self.driver = webdriver.Chrome(options=options)
        self.wait = WebDriverWait(self.driver, 10).until

    def baidu(self):
        self.driver.get('http://www.baidu.com')
        self.driver.find_element(By.XPATH, '//*[@id="kw"]').send_keys('六把刀个人博客')
        self.driver.find_element(By.XPATH, '//*[@id="su"]').click()
        self.wait(
            EC.presence_of_element_located((By.XPATH, "//a[contains(text(), 'www.liubadao.com')]"))
        ).click()
        self.driver.switch_to_window(self.driver.window_handles[-1])
        self.wait(
            EC.presence_of_element_located((By.XPATH, '//p[contains(text(), "六把刀(全贱架构师)")]'))
        ).click()
        time.sleep(random.randint(1, 4))
        self.driver.quit()